// stores/user.js
import {
	defineStore
} from 'pinia'
import {
	request
} from '@/utils/request'
import {
	silentLogin
} from '@/utils/auth'
import {
	loginByWechatCode,
	registerUser
} from '@/api/login' // 新增registerUser导入

export const useUserStore = defineStore('user', {
	state: () => ({
		userInfo: null,
		loading: false,
		error: null,
		pageStatus: 'not_logged' // not_logged/logging/need_register/logged_in
	}),

	actions: {
		// 初始化用户信息（从本地存储加载）
		initUserInfo() {
			try {
				const cached = uni.getStorageSync('userInfo')
				if (cached) {
					this.userInfo = JSON.parse(cached)
				}
			} catch (e) {
				console.error('解析用户信息缓存失败:', e)
				this.clearUserInfo()
			}
		},
		// 更新页面状态
		setPageStatus(status) {
			this.pageStatus = status
		},
		// 微信登录
		async wechatLogin() {
			console.log('开始测试uni.login');
			const [err, res] = await uni.login({
				provider: 'weixin'
			});
			console.log('测试结果:', err, res);
			// try {
			// 	this.setLogging();
			// 	console.log('1. 开始微信登录');

			// 	// 1. 获取微信code
			// 	const [err, loginRes] = await uni.login({
			// 		provider: 'weixin'
			// 	});
			// 	if (err) throw new Error(err.errMsg);
			// 	console.log('2. 获取微信code成功:', loginRes.code);

			// 	// 2. 调用登录接口
			// 	let res;
			// 	try {
			// 		res = await loginByWechatCode({
			// 			js_code: loginRes.code,
			// 			lang_code: 'zh'
			// 		});
			// 		console.log('3. 登录接口响应:', res);
			// 	} catch (apiError) {
			// 		console.error('登录接口请求异常:', apiError);
			// 		throw new Error('登录接口请求失败');
			// 	}

			// 	// 3. 处理响应
			// 	const code = Number(res.code); // 确保是数字
			// 	if (code === 200) {
			// 		await this.handleLoginSuccess(res.data);
			// 		this.setLoggedIn();
			// 		return {
			// 			success: true
			// 		};
			// 	} else if (code === 402) {
			// 		console.log('4. 需要注册，openid:', res.data?.openid);
			// 		this.setNeedRegister();
			// 		return {
			// 			needRegister: true,
			// 			openid: res.data?.openid || '',
			// 			loginCode: loginRes.code
			// 		};
			// 	} else {
			// 		throw new Error(res.message || `未知错误: ${res.code}`);
			// 	}
			// } catch (error) {
			// 	console.error('微信登录流程异常:', error);
			// 	this.setNotLogged();
			// 	throw error;
			// }
		},
		// 明确的状态转换方法
		setLoggedIn() {
			console.log('Pinia: 设置logging状态'); // 🔴 检查这里
			this.pageStatus = 'logged_in'
		},

		setNeedRegister() {
			this.pageStatus = 'need_register'
		},

		setNotLogged() {
			this.pageStatus = 'not_logged'
		},

		setLogging() {
			this.pageStatus = 'logging'
		},

		// 检查登录状态
		async checkAuthStatus() {
			try {
				this.loading = true
				this.pageStatus = 'logging'
				// 先从本地加载
				this.initUserInfo()

				const token = uni.getStorageSync('token')
				if (!token?.access_token) {
					this.setPageStatus('not_logged')
					return false
				}

				// 如果有token但无用户信息，尝试获取
				if (!this.userInfo && token.access_token) {
					const res = await silentLogin()
					if (res.code === 200) {
						this.setPageStatus('logged_in')
						return true
					}
				}

				// 检查token有效期
				if (token.expires_at <= Date.now() + 300000) {
					const res = await silentLogin() // 触发静默登录更新token
					if (res.code !== 200) {
						this.clearUserInfo()
						this.setPageStatus('not_logged')
						return false
					}
				}

				this.setPageStatus('logged_in')
				return true
			} catch (error) {
				console.error('检查登录状态失败:', error)
				this.pageStatus = 'not_logged'
				this.clearUserInfo()
				this.setPageStatus('not_logged')
				return false
			} finally {
				this.loading = false
			}
		},

		// 更新用户信息
		async updateUserInfo(updateData) {
			this.loading = true
			this.error = null
			try {
				const res = await request({
					url: '/userinfo/updateUserInfo',
					method: 'POST',
					data: updateData
				})

				// 合并更新后的数据
				const updatedInfo = {
					...this.userInfo,
					...res.data
				}
				this.setUserInfo(updatedInfo)

				return res.data
			} catch (error) {
				this.error = error.message || '更新用户信息失败'
				throw error
			} finally {
				this.loading = false
			}
		},
		async fetchUserInfo() {
			try {

				this.loading = true
				const res = await getUsInfo()

				if (res.code === 200) {
					this.setUserInfo({
						...res.data,
						// 转换字段名保持一致性
						policyNum: res.data.policy_num,
						supplyDemandNum: res.data.supply_demand_num,
						talentsNum: res.data.talents_num,
						spaceNum: res.data.space_num
					})
					return res.data
				} else {
					throw new Error(res.message || '获取用户信息失败')
				}
			} catch (error) {
				console.error('获取用户信息失败:', error)
				throw error
			} finally {
				this.loading = false
			}
		},
		// 设置用户信息（内部方法，处理持久化）

		setUserInfo(info) {
			// if (!this.validateUserData(info)) {
			// 	console.error('用户数据不完整:', info)
			// 	throw new Error('用户数据不完整')
			// }
			// 确保数据结构完整
			const fullUserInfo = {
				openid: info.openid,
				nickname: info.nickname || '未设置昵称',
				avatar: info.avatar || '/static/images/user/head.svg',
				phone: info.phone || '',
				gender: info.gender || 0,
				realName: info.real_name || '',
				langCode: info.lang_code || 'zh',
				isAuth: info.is_auth === 1,
				policyNum: info.policyNum || info.policy_num || 0,
				supplyDemandNum: info.supplyDemandNum || info.supply_demand_num || 0,
				talentsNum: info.talentsNum || info.talents_num || 0,
				spaceNum: info.spaceNum || info.space_num || 0
			}

			this.userInfo = fullUserInfo

			// 统一使用同步存储
			try {
				uni.setStorageSync('userInfo', JSON.stringify(fullUserInfo))
				console.log('用户信息存储成功')
			} catch (e) {
				console.error('用户信息存储失败:', e)
				// 可以尝试清理部分数据后重试
				const basicInfo = {
					user_id: fullUserInfo.user_id,
					openid: fullUserInfo.openid,
					avatar: fullUserInfo.avatar
				}
				uni.setStorageSync('userInfo', JSON.stringify(basicInfo))
			}
		},
		// validateUserData(data) {
		// 	if (!data) return false
		// 	const requiredFields = ['user_id', 'openid']
		// 	return requiredFields.every(field => data[field] !== undefined)
		// },
		// 清除用户信息
		clearUserInfo() {
			this.userInfo = null
			this.error = null
			this.pageStatus = 'not_logged'
			// 清除所有认证相关数据
			// uni.removeStorageSync('userInfo')
			// uni.removeStorageSync('token')
			// uni.removeStorageSync('refresh_token')
			// uni.removeStorage({
			// 	key: 'userInfo',
			// 	success: () => console.log('用户信息清除成功'),
			// 	fail: (err) => console.error('用户信息清除失败:', err)
			// })
		},
		async logout() {
			this.userInfo = null
			this.pageStatus = 'not_logged'
			// uni.removeStorageSync('token')
			// uni.removeStorageSync('refresh_token')
		},

	},

	getters: {
		isLoggedIn: (state) => !!state.userInfo,
		// 其他需要的计算属性...
		username: (state) => state.userInfo?.username || '',
		avatar: (state) => state.userInfo?.avatar || '/static/default-avatar.png'
	}
})